package com.unionftech.content_login.ui.register

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewTreeObserver
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.unionftech.common.R.color
import com.unionftech.common.R.drawable
import com.unionftech.common.R.string
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ApiException
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.bean.toastTimeout
import com.unionftech.common.common.adapter.CommonFragmentStateAdapter
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.recaptcha.RecaptchaUtil
import com.unionftech.common.router.RouterPath
import com.unionftech.common.utils.ActivityCollector
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SignUtils
import com.unionftech.common.utils.SpUtils
import com.unionftech.common.utils.StatusBarUtil
import com.unionftech.common.utils.ToastUtils
import com.unionftech.content_login.R
import com.unionftech.content_login.bean.LoginTokenInfo
import com.unionftech.content_login.bean.request.RegisterRequest
import com.unionftech.content_login.contract.RegisterContract
import com.unionftech.content_login.presenter.RegisterPresenter
import com.unionftech.content_login.service.LoginConstants
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.content_login.ui.login.UFLoginActivity

@Route(
    path = RouterPath.RegisterActivityInfo.PATH, name = RouterPath.RegisterActivityInfo.NAME
)
class UFRegisterActivity : BaseMvpActivity(),
    RegisterContract.IRegisterView, IUpdate {
    private val mTvHaveAccount by lazy { mRootView.findViewById<TextView>(R.id.tv_have_account) }
    private val mTvRegisterTitle: TextView by lazy { mRootView.findViewById(R.id.tv_register_title) }
    private val mTvGotoLogin: TextView by lazy { mRootView.findViewById(R.id.tv_goto_login) }
    private val mTabLayout: TabLayout by lazy { mRootView.findViewById(R.id.tab_layout) }
    private val mViewPager: ViewPager2 by lazy { mRootView.findViewById(R.id.view_pager) }

    private lateinit var mFragments: List<BaseFragment>
    private lateinit var mTitles: List<String>
    private lateinit var mAdapter: CommonFragmentStateAdapter
    private lateinit var mEmailRegisterFragment: EmailRegisterFragment
    private lateinit var mPhoneRegisterFragment: PhoneRegisterFragment
    private var mPublicKeyStr: String = ""
    private var mInitIndex = 1
    private var mObserver: ViewTreeObserver.OnGlobalLayoutListener? = null


    @InjectPresenter
    private lateinit var mRegisterPresenter: RegisterPresenter

    companion object {
        private const val TAG = "UFRegisterActivity"


        @JvmStatic
        fun startThis(context: Context) {
            val intent = Intent(context, UFRegisterActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }


    override fun initLayout() = R.layout.activity_ufregister

    override fun initData() {
        super.initData()
        mEmailRegisterFragment = EmailRegisterFragment.newInstance()
        mPhoneRegisterFragment = PhoneRegisterFragment.newInstance()
        mFragments = listOf(mEmailRegisterFragment, mPhoneRegisterFragment)
        mTitles = listOf(
            DynamicResourceManager.getString(mContext, string.email),
            DynamicResourceManager.getString(mContext, string.phone)
        )
        mAdapter = CommonFragmentStateAdapter(this)
        mAdapter.addFragment(mFragments)
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvRegisterTitle.text = DynamicResourceManager.getString(mContext, string.sign_up)
        mTvGotoLogin.text = DynamicResourceManager.getString(mContext, string.log_in)
        mTvHaveAccount.text =
            DynamicResourceManager.getString(mContext, string.already_have_account)
    }

    override fun setListener() {
        super.setListener()
        mEmailRegisterFragment.setRegisterListener(::requestRegister)
        mPhoneRegisterFragment.setRegisterListener(::requestRegister)
        mTvGotoLogin.setOnClickListener(this)
        mObserver = ViewTreeObserver.OnGlobalLayoutListener {
            mViewPager.viewTreeObserver.removeOnGlobalLayoutListener(mObserver)
            mViewPager.setCurrentItem(mInitIndex, false)
            getPublicKey()
            getCountryInfoByIp()
        }
        mViewPager.viewTreeObserver.addOnGlobalLayoutListener(mObserver)
    }

    override fun setView() {
        super.setView()
        initTitleBar()
        val textPaint = mTvGotoLogin.paint
        textPaint.flags = Paint.UNDERLINE_TEXT_FLAG //下划线
        textPaint.isAntiAlias = true //抗锯齿
        mViewPager.adapter = mAdapter
        mViewPager.offscreenPageLimit = 1
        TabLayoutMediator(mTabLayout, mViewPager) { tab, position ->
            tab.text = mTitles[position]
        }.attach()
        loadData()
    }

    override fun statusBar() {
        StatusBarUtil.immersive(this)
        StatusBarUtil.setNavbarColor(
            this, mContext.getColor(color.color_white)
        )
        StatusBarUtil.darkMode(this, false)
    }

    private fun initTitleBar() {
        hideCenterTitle()
        showBackImg(drawable.ic_title_back_white)
        mRootView.setBackgroundResource(R.drawable.ic_login_bg)
        setRightTextColor(mContext.getColor(color.color_7532FF))
        setRightImg(drawable.ic_headphones_white) {
            //TODO:正在开发
            ToastUtils.longToast(
                DynamicResourceManager.getString(
                    mContext, string.developing
                )
            )
        }
    }

    private fun requestRegister(requestBean: RegisterRequest) {
        //对密码进行加密
        SignUtils.encrypt(
            SignUtils.loadPublicKeyByStr(mPublicKeyStr), requestBean.encryptPassword.toByteArray()
        )?.also {
            val lastRequest = requestBean.copy(
                encryptPassword = it
            )
            mRegisterPresenter.unionfRegister(lastRequest)
        }
    }

    override fun loadData() {
        super.loadData()
    }

    private fun getCountryInfoByIp() {
        val countryInfo = GlobalInfoManager.getInstance().getCountryInfo()
        if (countryInfo != null) {
            updateCountryInfoByIp(countryInfo)
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_COUNTRY_INFO)
        }
    }

    private fun getPublicKey() {
        val publicKeyStr = GlobalInfoManager.getInstance().getPublicKeyStr()
        if (!TextUtils.isEmpty(publicKeyStr)) {
            mPublicKeyStr = publicKeyStr
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_PUBLIC_KEY)
        }
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.tv_goto_login -> gotoLogin()
        }
    }

    override fun backPressed(): Boolean {
        //fixme:产品要求永远返回账号密码登录页面
        UFLoginActivity.startThis(mActivity)
        return true
    }

    private fun gotoLogin() {
        UFLoginActivity.startThis(mActivity)
    }

    override fun onUpdate(obj: Any?) {
        when (obj) {
            is String -> {
                mPublicKeyStr = obj
            }

            is CountryInfo -> {
                updateCountryInfoByIp(obj)
            }
        }
    }

    private fun updateCountryInfoByIp(countryInfo: CountryInfo) {
        if (::mEmailRegisterFragment.isInitialized) {
            mEmailRegisterFragment.setCountryInfo(countryInfo)
        }
        if (::mPhoneRegisterFragment.isInitialized) {
            mPhoneRegisterFragment.setCountryInfo(countryInfo)
        }
    }

    override fun registerResult(response: ResponseResult<LoginTokenInfo>) {
        //注册且登录成功的吐司
        if (response.code == LoginConstants.Code.REGISTER_LOGIN_SUCCESS
            || response.code == ResponseResult.SUCCESS_CODE
        ) {
            if (response.code == LoginConstants.Code.REGISTER_LOGIN_SUCCESS) {
                response.toast()
            }
            gotoMain()
            mEmailRegisterFragment.resetData()
            mPhoneRegisterFragment.resetData()
        } else {
            LogUtils.e(
                TAG, "handleAllPhoneRegex error code: ${response.code} msg:${response.msg}"
            )
            if (ApiException.isTimeout(response.code)) {
                response.toastTimeout()
            } else {
                response.toast()
            }
        }
    }

    private fun gotoMain() {
//        SpUtils.getInstance()
//            .put(LoginConstants.Key.LOGIN_WAY, LoginConstants.Constant.LOGIN_BY_ACCOUNT)
        ARouter.getInstance().build(RouterPath.UFUFMainStandardActivityInfo.PATH).navigation()
        ActivityCollector.finishAll()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mAdapter.getFragment(mViewPager.currentItem)
            ?.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        RecaptchaUtil.getInstance().destroy()
        super.onDestroy()
    }

}